import { h } from 'vue';
import Button from 'ant-design-vue/es/button/index.js';
import Space from 'ant-design-vue/es/space/index.js';
import vueGlobal from '../../vueGlobal.js';

export default class StaticDataForm {
  constructor(formOptions) {
    this.formOptions = {};
    if (typeof formOptions === 'object' && formOptions) {
      this.formOptions = Object.keys(formOptions).reduce((res, key) => {
        key = key.split(',');
        return key.reduce((res, k) => {
          return Object.assign(res, { [k]: formOptions[key] });
        }, res);
      }, {});
    }
    this.openStaticDataForm = (e) => {
      // Ø 苹果电脑
      // O
      // if (e.ctrlKey && e.shiftKey && e.altKey && e.key === 'Ø') {
      if (e.ctrlKey && e.shiftKey && e.altKey && e.key === 'O') {
        let $route = vueGlobal.get('$route');
        let configs = this.formOptions[$route.name];
        if (!configs || typeof configs !== 'object') {
          return;
        }
        if (Array.isArray(configs)) {
          configs = { options: configs };
        }
        const footer = {
          name: 'Footer',
          methods: {
            onOk() {
              this.$emit('ok');
            },
            onCancel() {
              this.$emit('cancel');
            },
            onReset() {
              this.$emit('trigger', (view) => {
                view.reset();
                this.$emit('ok');
              });
            },
          },
          render() {
            return h(Space, {}, [
              h(Button, { size: 'large', type: 'primary', onClick: this.onOk }, ['确认']),
              h(Button, { size: 'large', onClick: this.onReset }, ['重置']),
              h(Button, { size: 'large', onClick: this.onCancel }, ['取消']),
            ]);
          },
        };
        vueGlobal.get('$dialog', ($dialog) => {
          $dialog({
            content: () => import('./view.vue'),
            contentProps: { options: configs.options },
            dialogProps: {
              movable: true,
              title: '数据录入（如有示例，请按照示例填写，引号等符号都是必要的！）',
              width: 'large',
              footer: footer,
              dialogStyle: configs.position || {},
            },
          });
        });
      }
    };
  }
  register() {
    if (this.formOptions && typeof this.formOptions === 'object') {
      window.addEventListener('keyup', this.openStaticDataForm);
    }
  }
  unregister() {
    window.removeEventListener('keyup', this.openStaticDataForm);
  }
}
